
--[[
*********************************************************************************
** 
** Copyright 2021-2024 LuaOS
**
** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
** LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
** OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
** SOFTWARE.
** 
*********************************************************************************
]]--

----------------------------------------------------------------------------

local dirsep = os.dirsep();
local outdir = "~build";
local filter = {};
local _R = require("luaos.format");

----------------------------------------------------------------------------

local function hash_name(filename)
  filename = filename:gsub("%.lua$", "");
  filename = filename:gsub("^%.\\", "");
  filename = filename:gsub(dirsep, ".");
  return crypto.md5(filename);
end

----------------------------------------------------------------------------

local function compile(pathname)
  pathname = pathname or ".";
  local dir = os.opendir(pathname);
  if not dir then
    return;
  end
  for file, folder in pairs(dir) do
    local filename = pathname .. dirsep .. file;
    if folder == true then
	  compile(filename);
	elseif file:match("%.lua$") then
	  local hashname = hash_name(filename);
	  if filter[hashname] then
	    throw(_R("{filename} hash repeat"));
	  end
	  filter[hashname] = true;
	  local outname    = outdir .. "\\" .. hashname;
	  local result     = os.compile(filename, outname);
	  local output     = result and print or error;
      output(_R(" build {hashname} <- {filename}"));
	end
  end
  dir:close();
end

----------------------------------------------------------------------------

os.mkdir(outdir);
luaos.start(compile, ...);

----------------------------------------------------------------------------
